import json
import logging
import traceback
import os
import util


def function1(filepath, base_path, num, jsonstring):
    log_path = os.path.join(base_path, "log.log")
    try:
        # 传入指定的路径
        util.set_base_path(base_path)
        if num == "1":
            from air.air import fun_air
            return fun_air(filepath, jsonstring)
        elif num == "2":
            from sea.sea import fun_sea
            return fun_sea(filepath, jsonstring)
        elif num == "3":
            from si.si import fun_si
            return fun_si(filepath, jsonstring)
        elif num == "4":
            sht_name=util.config_df['air']['表名'].head(1).item()
            data_list=util.config_df['air']['现字段名'].to_list()
            data_list.append(sht_name)
            return json.dumps(data_list, ensure_ascii=False)
        elif num == "5":
            sht_name=util.config_df['sea']['表名'].head(1).item()
            data_list=util.config_df['sea']['现字段名'].to_list()
            data_list.append(sht_name)
            return json.dumps(data_list, ensure_ascii=False)
        elif num == "6":
            sht_name=util.config_df['si']['表名'].head(1).item()
            data_list=util.config_df['si']['现字段名'].to_list()
            data_list.append(sht_name)
            return json.dumps(data_list, ensure_ascii=False)
    except Exception as e:
        # 获取异常信息
        tb = traceback.format_exc()
        # 创建一个logger
        logger = logging.getLogger('my_logger')
        # 设置日志级别
        logger.setLevel(logging.ERROR)

        # 创建一个handler用于写入日志文件
        fh = logging.FileHandler(log_path, encoding='utf-8')

        # 定义handler的输出格式
        formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
        fh.setFormatter(formatter)
        # 给logger添加handler
        logger.addHandler(fh)
        # 记录异常
        logger.error(f"An exception occurred: {e}\n{tb}")
        return f"处理数据时发生错误: {e}"